package com.zhoug.demo.sendpush.huawei;

import androidx.annotation.NonNull;

import com.zhoug.common.utils.JsonUtils;
import com.zhoug.demo.sendpush.DataCallback;
import com.zhoug.demo.sendpush.http.HttpClient;
import com.zhoug.logging.Logger;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @description: 类的简要描述
 * @author: 35574
 * @date: 2025/11/4 16:42
 */
public class HuaweiPushServer {
    private static final String TAG = ">>>HuaweiPushServer";
    /**
     * 华为推送鉴权接口
     */
    private static final String AUTHENTICATION_URL = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
    /**
     * 华为推送接口 {0}为项目id
     */
    private static final String URL = "https://push-api.cloud.huawei.com/v2/{0}/messages:send";

    private static String projectId;
    private static String clientId;
    private static String clientSecret;

    public static void setProjectId(String projectId) {
        HuaweiPushServer.projectId = projectId;
    }

    public static void setClientId(String clientId) {
        HuaweiPushServer.clientId = clientId;
    }

    public static void setClientSecret(String clientSecret) {
        HuaweiPushServer.clientSecret = clientSecret;
    }

    /**
     * 鉴权
     */
    public static void authentication(@NonNull DataCallback<HuaweiPushToken> callback) {
        Disposable disposable = HttpClient.getInstance().getBaseRequests().huaweiAuthentication(AUTHENTICATION_URL, "client_credentials", clientId, clientSecret)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(body -> {
                    String result = body.string();
                    Logger.d(TAG, "鉴权结果: " + result);
                    HuaweiPushToken huaweiPushToken = JsonUtils.fromJson(result, HuaweiPushToken.class);
                    if (huaweiPushToken != null) {
                        huaweiPushToken.setClientId(clientId);
                        huaweiPushToken.setClientSecret(clientSecret);
                        huaweiPushToken.setExp_expiresTimeMillis(System.currentTimeMillis() + huaweiPushToken.getExpires_in()*1000L);
                        callback.onSuccess(huaweiPushToken);
                    } else {
                        callback.onFailure("鉴权失败");
                    }
                }, throwable -> {
                    callback.onFailure("鉴权失败:" + throwable.getMessage());
                });

    }

    public static void send(@NonNull HuaweiMessageBody messageBody, @NonNull HuaweiPushToken token,@NonNull DataCallback<SendResponseBody> callback) {
        Map<String, String> header = new HashMap<>();
        // Authorization:Bearer DgEBANE2XIFmElfpaaLAI7sQzIYvO4hHA1HYXYg8BMVziSY8vPfka25A+hSPDcnV3qg0Lp+ytTwIrVTd6yvNiM8ViTbBEHvcbQbhYQ==
        header.put("Authorization", String.format("%s %s",token.getToken_type(),token.getAccess_token()));
        Disposable disposable = HttpClient.getInstance().getBaseRequests().pushByHuawei(MessageFormat.format(URL,projectId), header, messageBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(body -> {
                    String result = body.string();
                    Logger.d(TAG, "消息发送结果: " + result);
                    SendResponseBody sendResponseBody = JsonUtils.fromJson(result, SendResponseBody.class);
                    if (sendResponseBody == null) {
                        callback.onFailure("消息发送失败: 没有返回结果");
                    } else if (sendResponseBody.isSuccess()) {
                        callback.onSuccess(sendResponseBody);
                    } else {
                        callback.onFailure("消息发送失败: 错误码:" + sendResponseBody.getCode() + ",错误描述" + sendResponseBody.getMsg());
                    }
                }, throwable -> {
                    callback.onFailure("消息发送失败: " + throwable.getMessage());
                });

    }

}
